<template>
  <div>
<!-- 面包屑导航区-->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
<!--      点击用户区域-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true ">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table border stripe :data="userList">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" width="180" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop = "email" width="180"></el-table-column>
        <el-table-column label="电话" prop = "mobile" width="180"></el-table-column>
        <el-table-column label="角色" prop = "role_name"></el-table-column>
        <el-table-column label="状态" prop = "mg_state" width="180">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
         <template slot-scope="scope">
<!--           编辑按钮-->
           <el-button type="primary" icon="el-icon-edit" size="mini" @click="editBtn(scope.row.id)"></el-button>
           <el-button type="warning" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
           <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start">
             <el-button type="danger" icon="el-icon-setting" size="mini" @click="setUserRoles(scope.row)"></el-button>
           </el-tooltip>
           
         </template>
        </el-table-column>
      </el-table>
<!--      分页器-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
<!--对话框-->
      <el-dialog
        title="提示"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="closeAddDialog">
<!--        表单区域-->
        <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addFrom.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addFrom.password"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addFrom.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addFrom.email"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      
<!--      修改用户对话框-->
      <el-dialog
        title="提示"
        :visible.sync="editDialogVisible"
        width="50%"
        >
        <el-form
          :model="editForm"
          :rules="editFromRules"
          ref="editFormRef"
          label-width="100px"
          @close="editDialogClosed">
          <el-form-item label="用户名" >
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSubmit">确 定</el-button>
        </span>
      </el-dialog>
<!--      分配角色对话框-->
      <el-dialog
        title="分配角色"
        :visible.sync="userRolesDialogVisible"
        width="50%"
        >
        <div>
          <p>当前的用户: {{userInfo.username}}</p>
          <p>当前的角色:{{userInfo.role_name}}</p>
          <p>
            <el-select v-model="userInfoId" placeholder="请选择" value="">
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
    <el-button @click="userRolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRoles">确 定</el-button>
  </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'User',
  data () {
    //邮箱的验证
    let emailReg = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      } else {
        return callback(new Error('请输入正确邮箱'))
      }
    }
    // 验证手机号的规则
    let checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      //用户列表集合
      userList: [],
      //总页数
      total: 0,
      //添加用户对话框
      addDialogVisible: false,
      //添加用户表单数据
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
     
      //添加用户表单验证规则
      addFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailReg, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFromRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailReg, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //修改功能对话框
      editDialogVisible: false,
      //存放修改对象的数据
      editForm: {
      
      },
      //编辑用户id
      editUserId: '',
      //分配角色
      userRolesDialogVisible: false,
      //用户信息
      userInfo: '',
      //获取的角色列表
      roles: [],
      //已选中的角色id
      userInfoId: ''
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    //查询出所有用户数据
    async getUsersList() {
      // eslint-disable-next-line no-unused-vars
      let{ data : res } = await this.$http.get(`users`, {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      // this.$message.success('获取用户列表成功')
      this.total = res.data.total
      this.userList = res.data.users
    },
    //页码改变时
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    handleCurrentChange(newNum) {
      this.queryInfo.pagenum = newNum
      this.getUsersList()
    },
    //监听状态按钮切换
    async userStateChange(userInfo) {
      //发送请求
      // eslint-disable-next-line no-unused-vars
      let { data : res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
      res.data.mg_state = userInfo.mg_state
    },
    //关闭添加用户
    closeAddDialog() {
      //重置表单
      this.$refs.addFromRef.resetFields()
    },
    //添加用户操作
    async addUser() {
      //先检测用户输入的信息是否合法
      this.$refs.addFromRef.validate(valid => {
        if (!valid) return this.$message.error('您输入的信息不合法')
      })
      //发送请求,获取数据
      let { data: res } = await this.$http.post(`users`, this.addFrom)
      // console.log(res)
      if (res.meta.status !== 201) return this.$message.error('添加用户失败')
      //隐藏动画框
      this.addDialogVisible = false
      //刷新页面
      this.getUsersList()
    },
    //修改功能按钮
    async editBtn(id) {
      //将获取的id保存起来
      this.editUserId = id
      let{ data : res } = await this.$http.get(`users/${id}`)
      this.editForm = res.data
      this.editDialogVisible = true
      //查询到用户之后,完成修改点击确认按钮,再次添加用户
    },
    //点击确定按钮
    async editSubmit() {
      // eslint-disable-next-line no-unused-vars
      let { data : res } = await this.$http.put(`users/${this.editUserId}`, {
        email :this.editForm.email,
        mobile: this.editForm.mobile
      })
      if (res.meta.status !== 200) return this.$message.error('修改用户失败')
      this.getUsersList()
      this.editDialogVisible = false
      this.$message.success('修改用户成功')
    },
    //关闭表单时清空
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //删除用户操作
    async deleteUser(id) {
      //发送请求
      // eslint-disable-next-line no-unused-vars
      let result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (result !== 'confirm') return this.$message.info('您已取消了删除')
      let { data : res } = await this.$http.delete(`users/${id}`)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUsersList()
    },
    //分配角色
    async setUserRoles (role) {
      //设置用户的信息
      this.userInfo = role
      this.userRolesDialogVisible = true
      //发送ajax请求,获取所有角色
      let { data: res } = await this.$http.get(`roles`)
      // eslint-disable-next-line no-undef
      this.roles = res.data
    },
    // 完成分配角色\
    async setRoles () {
      let { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.userInfoId
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.userRolesDialogVisible = false
      this.getUsersList()
    }
  }
}
//提交修改用户信息时,清空表单

</script>

<style scoped lang="less">

</style>
